package com.filesystem.shiro;

import com.filesystem.file.entity.User;
import com.filesystem.file.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Currency;

/**
 *  自定义Realm
 *  @author JayZhou
 */

/**
 * @Component 设置为组件， 不然在ShrioConfig  配置文件找 @Qualifier("userRealm") 会找不到
 */

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService iUserService;


    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权逻辑
        System.out.println("执行授权逻辑");
        return null;
    }


    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证逻辑
        System.out.println("执行认证逻辑");
        UsernamePasswordToken token = ( UsernamePasswordToken ) authenticationToken;
        //获取身份
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        //从数据库查询用户名
        User user = iUserService.selectByUserNamePassword(username,password);
        //模拟登录
        AuthenticationInfo authenticationInfo = null;
        if ( user != null ){
            authenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());
        }
        return authenticationInfo;
    }
}